<?php
$name = $_POST['name'];
$description = $_POST['description'];
$id = $_POST['id'];
//$pic = $_FILES['pic'];
if($name == "" or $description == ""){
    echo "<script>alert('对象名称和对象描述必须填写！');history.back();</script>";
    exit;
}
include_once "conn.php";
if($_FILES['pic']['error'] == 4){
    //说明不需要修改图片
    //直接更新数据库，只更新名字和描述
    $sql = "update object set name = '$name',description = '$description' where id = $id";
    $result = mysqli_query($conn,$sql);
    if($result){
        echo "<script>alert('编辑资料成功！');location.href='admin.php';</script>";
        exit;
    }
    else{
        echo "<script>alert('编辑资料失败！');history.back();</script>";
        exit;
    }
}
elseif($_FILES['pic']['error'] == 0){
    //说明是需要修改图片，且图片正常上传
    $fileName = $_FILES['pic']['name'];
    $array = explode('.',$fileName);
    if(count($array) == 1){
        //说明上传的文件木有扩展名
        echo "<script>alert('上传文件必须是图片类型，且有扩展名！');history.back();</script>";
        exit;
    }
    //判断文件类型是否是图片
    $fileType = $_FILES['pic']['type'];
    $fileExtArray = ["image/png","imag/jpg","image/gif"];
    if(!in_array($fileType,$fileExtArray)){
        echo "<script>alert('上传文件只支持JPG,PNG,GIF类型');history.back();</script>";
        exit;
    }
    //判断文件尺寸,规定文件大小不得超过800K
    $size = $_FILES['pic']['size'] / 1024;
    if($size > 800){
        echo "<script>alert('文件大小不得超过800KB');history.back();</script>";
        exit;
    }
    $ext = end($array);
    $fileName = './images/'.time().rand(1000,9999).".".$ext;
    if(move_uploaded_file($_FILES['pic']['tmp_name'],$fileName)){
        //上传成功
        //将相关信息写入数据库
        $sql = "update object set name = '$name',description = '$description',pic='$fileName' where id = $id";
        $result = mysqli_query($conn,$sql);
        if($result){
            echo "<script>alert('编辑成功！');location.href='admin.php';</script>";
        }
        else{
            echo "<script>alert('编辑出错！');history.back();</script>";
        }
    }
    else{
        echo "<script>alert('上传文件出错！');history.back();</script>";
    }
}
else{
    echo "<script>alert('上传文件出错！');history.back();</script>";
}